import 'dart:async';

import 'package:async/src/typed/stream_subscription.dart';
import 'package:async_test/src/utils.dart';
import '../common/test_page.dart';

class StreamSubscriptionTestPage extends TestPage {
  late StreamController controller;
  late StreamSubscription wrapper;
  late bool isCanceled;

  setUp() {
    isCanceled = false;
    controller = StreamController<Object>(onCancel: () {
      isCanceled = true;
    });
    wrapper = TypeSafeStreamSubscription<int>(controller.stream.listen(null));
  }

  StreamSubscriptionTestPage(super.title) {
    test('wrapper.onData()', () {
      setUp();
      wrapper.onData((data) {
        expect(data);
      });
      controller.add(1);
    });

    test('wrapper.onError()', () {
      setUp();
      wrapper.onError((error) {
        expect(error);
      });
      controller.addError('oh no');
    });

    test('wrapper.onDone()', () {
      var value = 0;
      setUp();
      wrapper.onDone(() {
        value++;
      });
      controller.close();
      expect(value);
    });

    test('wrapper.pause(), wrapper.resume(), and wrapper.isPaused', () async {
      setUp();
      expect(wrapper.isPaused);

      wrapper.pause();
      await flushMicrotasks();
      expect(controller.isPaused);
      expect(wrapper.isPaused);

      wrapper.resume();
      await flushMicrotasks();
      expect(controller.isPaused);
      expect(wrapper.isPaused);
    });

    test('cancel()', () async {
      setUp();
      wrapper.cancel();
      await flushMicrotasks();
      expect(isCanceled);
    });

    test('asFuture()', () async {
      setUp();
      expect(wrapper.asFuture(12));
      controller.close();
    });

    test('TypeSafeStreamSubscription<int>(controller.stream.listen(null)).onData()', () {
      setUp();
      expect(() {
        controller = StreamController<Object>();
        wrapper = TypeSafeStreamSubscription<int>(controller.stream.listen(null));
        wrapper.onData((_) {});
        controller.add('foo');
      });
    });
  }

}